package com.github.aloxc.plugin.restplus.listener;

import com.github.aloxc.plugin.restplus.common.Consts;
import com.github.aloxc.plugin.restplus.entity.EnvironmentConfig;
import com.github.aloxc.plugin.restplus.entity.RestConfig;
import com.github.aloxc.plugin.restplus.i18n.I18Bundle;
import com.github.aloxc.plugin.restplus.navigator.RestServiceDetail;
import com.github.aloxc.plugin.restplus.navigator.RestServicesNavigator;
import com.github.aloxc.plugin.restplus.popup.PopupBalloon;
import com.github.aloxc.plugin.restplus.utils.StringUtils;
import com.github.aloxc.plugin.restplus.utils.ToolkitUtil;
import com.intellij.openapi.ide.CopyPasteManager;

import javax.swing.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 拷贝url
 */
public class CopyUrlActionListener implements ActionListener {
    private JComponent component;
    private RestServiceDetail restServiceDetail;

    public CopyUrlActionListener(RestServiceDetail restServiceDetail) {

        this.restServiceDetail = restServiceDetail;
    }

    public void setComponent(JComponent component) {
        this.component = component;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (StringUtils.isNullOrEmpty(restServiceDetail.getUrl())) {
            return;
        }
        boolean isFull = false;
        JMenuItem item = (JMenuItem) e.getSource();
        if (item.getIcon().equals(Consts.Icons.FULL_URL)) {
            isFull = true;
        }
        String tempUrl = restServiceDetail.getUrl();
        RestConfig config = restServiceDetail.getProject().getComponent(RestServicesNavigator.class).getConfig();
        EnvironmentConfig environmentConfig = null;
        if (config != null && config.getEnv() != null && config.getEnv().size() > 0) {
            Map<String, EnvironmentConfig> envMap = config.getEnv();
            for (String envName : envMap.keySet()) {
                if (envMap.get(envName).isSelected()) {
                    environmentConfig = envMap.get(envName);
                    break;
                }
            }
        }
        if (restServiceDetail.getRequestParamsTextArea() != null) {
            String requestParamsText = restServiceDetail.getRequestParamsTextArea().getText();
            Map<String, Object> paramMap = ToolkitUtil.textToParamMap(requestParamsText);
            Set<String> usedKeySet = new HashSet<>(2 << 3);
            if (paramMap != null && paramMap.size() > 0) {
                String prev = tempUrl;
                for (String key : paramMap.keySet()) {
                    tempUrl = tempUrl.replaceFirst("\\{(" + key + "[\\s\\S]*?)\\}", String.valueOf(paramMap.get(key)));
                    if (!prev.equals(tempUrl)) {
                        usedKeySet.add(key);
                    }
                    prev = tempUrl;
                }
            }
            usedKeySet.stream().forEach(k -> paramMap.remove(k));
            String params = ToolkitUtil.textToRequestParam(paramMap);
            if (params.length() != 0) {
                // 包含了参数
                if (tempUrl.contains("?")) {
                    tempUrl += "&" + params;
                } else {
                    tempUrl += "?" + params;
                }
            }
        }

        // 完整url
        String responseText = tempUrl;
        boolean https = environmentConfig.isHttps();
        String context = environmentConfig.getContext();
        String tContext = context;
        if (!StringUtils.isNullOrEmpty(tContext)) {
            if (!tContext.startsWith("/")) {
                tContext = "/" + tContext;
            }
            if (context.endsWith("/")) {
                tContext = context.substring(0, context.length() - 1);
            }
        } else {
            tContext = "";
        }
        if (isFull) {
            tempUrl = (https ? "https://" : "http://") + environmentConfig.getHost() + ":" + environmentConfig.getPort() + tContext + tempUrl;
        }
        CopyPasteManager.getInstance().setContents(new StringSelection(tempUrl));
        PopupBalloon.showPopupBalloon(component,
                (isFull ?
                        String.format(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.copy.servicefullurl.text"), tempUrl, tempUrl) :
                        String.format(I18Bundle.getMessage("com.github.aloxc.plugin.restplus.copy.serviceurl.text"), tempUrl)), false);
    }


}